package com.zgc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgc.common.R;
import com.zgc.entity.EmpRole;
import com.zgc.entity.Role;
import com.zgc.service.EmpRoleService;
import com.zgc.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private EmpRoleService empRoleService;

    /**
     * 新增角色
     *
     * @param role
     * @return
     */
    @PostMapping
    // @CheckPermission
    public R<String> save(HttpServletRequest request, @RequestBody Role role) {
        log.info("新增角色，角色信息：{}", role.toString());
        roleService.save(role);
        return R.success("新增角色成功");
    }

    /**
     * 角色信息分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @return
     */
    @GetMapping("/page")
    // @CheckPermission
    public R<Page> page(int page, int pageSize) {
        log.info("page = {},pageSize = {}", page, pageSize);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper();
        //添加排序条件
        //queryWrapper.orderByDesc(Role::getUpdateTime);
        //执行查询
        roleService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id修改角色信息
     *
     * @param role
     * @return
     */
    @PutMapping
    // @CheckPermission
    public R<String> update(HttpServletRequest request, @RequestBody Role role) {
        roleService.updateById(role);
        return R.success("角色信息修改成功");
    }

    @GetMapping("/{id}")
    //@CheckPermission
    public R<Role> getById(@PathVariable Long id) {
        Role role=roleService.getById(id);
        if(null !=role){
            return R.success(role);
        }
        return R.error("角色没查到");
    }

    //数据的回填
    @GetMapping("/emp/{empid}")
    public R<String> getByRoleByEmp(@PathVariable String empid) {
        LambdaQueryWrapper<EmpRole> queryWrapper = new LambdaQueryWrapper();
        //添加排序条件
        queryWrapper.eq(EmpRole::getEmpId,empid);
        EmpRole empRole= empRoleService.getOne(queryWrapper);
        if(null==empRole){
            return R.success("");
        }
        return R.success(empRole.getRoleId());
    }


    @GetMapping("/all")
    public R<List> getAllRole(){
        List<Role> list= roleService.list();
        return R.success(list);
    }



}
